package eproject.mm.com.projectsupervision.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.chanven.lib.cptr.PtrClassicFrameLayout;
import com.chanven.lib.cptr.loadmore.OnLoadMoreListener;
import com.chanven.lib.cptr.recyclerview.RecyclerAdapterWithHF;
import com.google.gson.Gson;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import eproject.mm.com.projectsupervision.R;
import eproject.mm.com.projectsupervision.activity.ProblemDealActivity;
import eproject.mm.com.projectsupervision.activity.ProblemInfoActivity;
import eproject.mm.com.projectsupervision.activity.ProblemListActivity;
import eproject.mm.com.projectsupervision.adapter.BaseRecyclerViewAdapter;
import eproject.mm.com.projectsupervision.adapter.ProblemRecyclerViewAdapter;
import eproject.mm.com.projectsupervision.util.HttpUtil;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import com.bigkoo.alertview.OnItemClickListener;

/**
 * Created by momotea on 2018/3/19.
 */

public class ProblemFragment extends LazyFragment implements ProblemRecyclerViewAdapter.onItemClickListener{
    RecyclerView rv_list;
    ProblemRecyclerViewAdapter adapter;

    int page = 1;
    String type;

    LoadingDialog loadingDialog = null;
    private PtrClassicFrameLayout ptrFrameLayout;

    List listData = new ArrayList();
    private RecyclerAdapterWithHF mAdapter;

    AlertView problemActionAlertView;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        if(getArguments() != null){
            type = getArguments().getString("type","");
        }
        return inflater.inflate(R.layout.fragment_problem, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        rv_list = (RecyclerView)getView().findViewById(R.id.rv_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_list.setLayoutManager(layoutManager);

        adapter = new ProblemRecyclerViewAdapter(getContext(), listData);
        mAdapter = new RecyclerAdapterWithHF(adapter);

        adapter.setOnItemClickLitsener(this);

        rv_list.setAdapter(mAdapter);

        ptrFrameLayout = (PtrClassicFrameLayout)getView().findViewById(R.id.ptrFL_list);

        //下拉刷新支持时间
        ptrFrameLayout.setLastUpdateTimeRelateObject(this);
        //下拉刷新一些设置 详情参考文档
        ptrFrameLayout.setResistance(1.7f);
        ptrFrameLayout.setRatioOfHeaderHeightToRefresh(1.2f);
        ptrFrameLayout.setDurationToClose(200);
        ptrFrameLayout.setDurationToCloseHeader(1000);
        // default is false
        ptrFrameLayout.setPullToRefresh(false);
        // default is true
        ptrFrameLayout.setKeepHeaderWhenRefresh(true);
        //进入Activity就进行自动下拉刷新
        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrFrameLayout.autoRefresh();
            }
        }, 100);

        ptrFrameLayout.setPtrHandler(new com.chanven.lib.cptr.PtrDefaultHandler() {
            //在这里进行数据加载
            public void onRefreshBegin(com.chanven.lib.cptr.PtrFrameLayout frame) {
                page = 1;
                loadList();
            }
        });
        ptrFrameLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
                page++;
                loadList();
            }
        });

    }

    public void onItemClick(View view, int position){
        clickedProblemMap = (Map)adapter.getItemAt(position);
        Intent intent = new Intent(getActivity(), ProblemInfoActivity.class);
        Bundle bundle=new Bundle();

        Iterator it = clickedProblemMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            Object key = entry.getKey();
            Object value = entry.getValue();
            if(value.getClass().getSimpleName().equals("String")) {
                bundle.putString((String) key, (String) value);
            }
        }

        intent.putExtras(bundle);
        startActivityForResult(intent,0);
    }
    Map clickedProblemMap = null;
    public void onItemLongClick(View view, int position){
        return;
//        clickedProblemMap = (Map)adapter.getItemAt(position);
//        if(problemActionAlertView == null) {
//            problemActionAlertView = new AlertView(null, null, "取消", null,
//                    new String[]{"问题查看", "问题整改", "问题复查"},
//                    getContext(), AlertView.Style.Alert, new OnAlertItemClickListener());
//        }
//        problemActionAlertView.show();
    }
    private void loadList(){
        loadingDialog = new LoadingDialog(getContext());
        loadingDialog.setLoadingText("加载中...").show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String url = "";
                    if(type == null){
                        handler.sendMessage(handler.obtainMessage(2, null));
                    }else {
                        url = "/getProblemListBySupPerson?type="+type+"&page=" + String.valueOf(page) + "&limit=10";

                        String listStr = HttpUtil.get(url);

                        handler.sendMessage(handler.obtainMessage(1, listStr));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String listStr = (String)msg.obj;
                    Gson gson=new Gson();
                    Map resultMap = gson.fromJson(listStr, Map.class);
                    if (resultMap != null && (boolean) resultMap.get("success")) {
                        List rows = (List) resultMap.get("rows");
                        int pages = Integer.parseInt((String)resultMap.get("pages"));

                        loadingDialog.close();
                        if(page==1) {
                            listData.clear();
                            listData.addAll(rows);

                            adapter.notifyDataSetChanged();
                            ptrFrameLayout.refreshComplete();

                            if(page < pages){
                                if (!ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(true);
                                }
                            }
                        }else{
                            listData.addAll(rows);
                            adapter.notifyDataSetChanged();

                            ptrFrameLayout.loadMoreComplete(true);
                            if(page == pages){
                                if (ptrFrameLayout.isLoadMoreEnable()) {
                                    ptrFrameLayout.setLoadMoreEnable(false);
                                }
                            }
                        }
                    }
                    break;
                case 2:
                    loadingDialog.close();
                    ptrFrameLayout.refreshComplete();
                    if (ptrFrameLayout.isLoadMoreEnable()) {
                        ptrFrameLayout.setLoadMoreEnable(false);
                    }
                    break;
            }
        }
    };

    public void LazyLoad(){
        //loadList();
    }

    public class OnAlertItemClickListener implements com.bigkoo.alertview.OnItemClickListener{
        public void onItemClick(Object view, int position){
            if(position == 0){
                Intent intent = new Intent(getActivity(), ProblemInfoActivity.class);
                Bundle bundle=new Bundle();

                Iterator it = clickedProblemMap.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry entry = (Map.Entry) it.next();
                    Object key = entry.getKey();
                    Object value = entry.getValue();
                    if(value.getClass().getSimpleName().equals("String")) {
                        bundle.putString((String) key, (String) value);
                    }
                }

                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }else if(position == 1){
                problemActionAlertView.dismiss();

                Intent intent = new Intent(getActivity(), ProblemDealActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("type", "0");
                bundle.putString("problemid", (String)clickedProblemMap.get("id"));
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }else if(position == 2){
                problemActionAlertView.dismiss();
                Intent intent = new Intent(getActivity(), ProblemDealActivity.class);
                Bundle bundle=new Bundle();
                bundle.putString("type", "1");
                bundle.putString("problemid", (String)clickedProblemMap.get("id"));
                intent.putExtras(bundle);
                startActivityForResult(intent,0);
            }
        }
    }
}
